#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mpi.h"

int
main(int argc, char **argv)
{
	int size, rank, i;
	int success = 1;

	int sendbuf[2] = {1,2};
	int *recvbuf = NULL;
	int *displs,*recvcounts;
	printf("before init\n");
	
	MPI_Init(&argc, &argv);
	
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	printf("Size %d, Rank %d\n",size,rank);

	recvbuf = (int *)malloc(size*size*sizeof(int)); 
	displs = (int *)malloc(size*sizeof(int));
	recvcounts = (int *)malloc(size*sizeof(int));

	for(i = 0; i < size; i++)
	{
		recvcounts[i] = 2;
		displs[i] = i * 2;
	}
	printf("ALL_SEND: [%d, %d]\n",sendbuf[0],sendbuf[1]);
	MPI_Allgatherv(sendbuf,2,MPI_INT,recvbuf,recvcounts,displs, MPI_INT, MPI_COMM_WORLD);

	printf("ALL_RECV: [");
	for (i = 0; i < size*2; i++) {
		if (i % 2 == 0) {
			printf("%d,%d",recvbuf[i], recvbuf[i+1]);
			success = success && (recvbuf[i] == 1);
		} else {
			printf(",");
			success = success && (recvbuf[i] == 2);
		}
	}
	printf("]\n");
	
	MPI_Finalize();
	if (success == 1) {
		printf("SUCCESS\n");
	}
	return 0;
}

